<template>
  <div v-loading="loading.status" class="body">
    <div class="table_content">
      <div class="table_filtrate">
        <div
          v-if="jsAuthJudgment('manage')"
          class="tf_item"
          style="margin-right: 30px"
        >
          <div class="tag">商务</div>
          <el-select
            v-model="tableParams.business_uid"
            clearable
            size="mini"
            placeholder="请选择"
            :filterable="true"
            class="inp"
            @change="changeSelectBusinessuid"
          >
            <el-option
              v-for="item in business_select"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            >
              <span style="float: left">{{ item.nickname }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.group_name
              }}</span>
            </el-option>
          </el-select>
        </div>
        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">机构</div>
          <el-select
            v-model="tableParams.o_id"
            placeholder="请选择"
            clearable
            size="mini"
            :filterable="true"
            class="inp"
            no-data-text="请先选择商务"
          >
            <el-option
              v-for="item in organization_select"
              :key="item.id"
              :label="item.name"
              :value="Number(item.id)"
            />
          </el-select>
        </div>
        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">助贷类型</div>
          <el-select
            v-model="tableParams.loan_type"
            placeholder="助贷类型"
            clearable
            size="mini"
            :filterable="true"
            class="inp"
            no-data-text="请先选择商务"
          >
            <el-option label="全国" value="nationwide" />
            <el-option label="地区" value="region" />
          </el-select>
        </div>
        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">推送状态</div>
          <el-select
            v-model="tableParams.push_status"
            placeholder="推送状态"
            clearable
            size="mini"
            :filterable="true"
            class="inp"
            no-data-text="推送状态"
          >
            <el-option label="开启" value="1" />
            <el-option label="关闭" value="0" />
          </el-select>
        </div>
        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">进件状态</div>
          <el-select
            v-model="tableParams.entry_status"
            placeholder="推送状态"
            clearable
            size="mini"
            :filterable="true"
            class="inp"
            no-data-text="进件状态"
          >
            <el-option label="开启" value="1" />
            <el-option label="关闭" value="0" />
          </el-select>
        </div>

        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">搜索</div>
          <el-input
            v-model="tableParams.fuzzy_search"
            class="input_fuzzy_search input"
            size="mini"
            placeholder="ID|名字"
            clearable
          />
        </div>

        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">计划名称</div>
          <el-input
            v-model="tableParams.plan_name"
            class="input_fuzzy_search input"
            size="mini"
            placeholder="计划名称"
            clearable
          />
        </div>

        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">状态</div>
          <el-select
            v-model="tableParams.status"
            placeholder="状态"
            clearable
            size="mini"
            :filterable="true"
            class="inp"
            no-data-text="进件状态"
          >
            <el-option label="正常" value="normal" />
            <el-option label="废弃" value="stop" />
          </el-select>
        </div>

        <div class="tf_item">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="loadTableData"
          >搜索</el-button>
        </div>
      </div>

      <div class="table_operate">
        <el-button
          class="btn_add"
          type="primary"
          size="mini"
          @click="handleToGoCreate"
        >添加</el-button>
      </div>

      <div class="table-card">
        <el-table
          v-loading="loading.table"
          class="table"
          :data="tableData.data"
          :border="true"
          :row-class-name="tableRowClassName"
           show-summary :summary-method="$_App_getSummaries"
          size="mini"
        >
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="plan_name" label="计划名称" width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span
                slot="reference"
                class="ellipsis custom-link"
                style="font-size: 12px"
              >{{ scope.row.plan_name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="产品名称" width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span
                slot="reference"
                class="ellipsis custom-link"
                style="font-size: 12px"
              >{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="organization.name"
            label="机构名称"
            width="120"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span
                slot="reference"
                class="ellipsis custom-link"
                style="font-size: 12px"
              >{{ scope.row.organization.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="loan_type" label="助贷类型" width="70">
            <template slot-scope="scope">
              <el-tag size="mini" plain effect="plain">{{
                scope.row.loan_type
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="organization.username" label="商务" width="110" />
          <el-table-column prop="organization_balance" label="余额" width="110" />
          <el-table-column
            prop="cm_expend_money"
            label="当月累计消耗"
            width="110"
          />
          <el-table-column prop="today_push_num" label="当天推送量" width="100" />
          <el-table-column label="剩余推送量" width="100">
            <template slot-scope="scope">
              {{ scope.row.today_push_max - scope.row.today_push_num }}
            </template>
          </el-table-column>
          <el-table-column prop="today_push_max" label="计划推送量" width="100" />
          <el-table-column prop="cooperative_price" label="合作价格" />
          <el-table-column prop="loan_type" label="运行状态" width="70">
            <template slot-scope="scope">
              <el-tag
                v-if="scope.row.operation_status == 'normal'"
                size="mini"
                plain
                effect="plain"
                type="success"
              >正常</el-tag>
              <el-tag
                v-else
                size="mini"
                plain
                effect="plain"
                type="danger"
              >停止</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="推送状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.push_status"
                :active-value="1"
                :inactive-value="0"
                @change="tableUpdateItem(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="进件状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.entry_status"
                disabled
                :active-value="1"
                :inactive-value="0"
                @change="tableUpdateItem(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="权重" />
          <el-table-column label="操作" width="90" fixed="right">
            <template slot-scope="scope">
              <el-link
                v-if="scope.row.status == 'stop'"
                class="handle"
                type="warning"
                @click="handleTableRegain(scope.$index, scope.row)"
              >恢复</el-link>
              <el-link
                v-show="scope.row.status == 'normal'"
                class="handle"
                type="primary"
                @click="handleTableEdit(scope.$index, scope.row)"
              >编辑</el-link>
              <!-- <el-link
                class="handle"
                type="primary"
                @click="handleProduceApi(scope.row)"
              >Api</el-link> -->
              <el-link
                v-show="scope.row.status == 'normal'"
                class="handle"
                type="danger"
                @click="handleTableDelete(scope.$index, scope.row)"
              >删除</el-link>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="!loading.table"
          class="table_pagination"
          :current-page="tableParams.page"
          :page-sizes="$pageSize"
          :page-size="tableParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleTableSizeChange"
          @current-change="handleTableCurrentChange"
        />
      </div>
    </div>

    <JsonTree ref="refJsonTree" />
  </div>
</template>

<script>
import {
  apiProductlistpage,
  apiProductUpdatePart,
  apiProductDelete,
  apiAgentList
} from '@/api/apiCommon'
import { apiOrganizationSelects } from '@/api/apiOrganization'
import { paramsDeleteNull } from '@/utils/common'
import { authJudgment } from '@/utils/appUtil'
import JsonTree from './jsonTree.vue'
export default {
  name: 'Index',
  components: {
    JsonTree
  },
  data() {
    return {
      tableParams: {
        page: 1,
        size: 30,
        business_uid: '',
        o_id: '',
        loan_type: '',
        push_status: '',
        entry_status: '',
        plan_name: '',
        status: 'normal'
      },
      tableData: {
        current_page: 1,
        data: [],
        last_page: 1,
        per_page: '30',
        total: 0
      },
      currentPage4: 1,
      business_select: [],
      organization_select: [],
      group: [],
      dialogConfig: {
        title: '添加人员'
      },
      table_loading: false,
      dialogFormVisible: false,
      fromViewCofing: {
        input_width: '120px',
        label_width: '120px'
      },
      form: {
        id: 0,
        account: '',
        password: '',
        password_confirmation: '',
        mobile: '',
        nickname: '',
        group_id: '',
        status: 'normal'
      },
      loading: {
        dialog_create: false,
        table: false
      }
    }
  },
  created() {
    var params = this.$route.query

    if (params.business_uid) {
      this.tableParams.business_uid = Number(params.business_uid)
    }
    if (params.business_uid && params.o_id) {
      this.tableParams.o_id = Number(params.o_id)
      this.reqApiOrganization(params.business_uid)
    }
    if (this.jsAuthJudgment('manage')) {
      this.reqApiAgent(this.jsAuthJudgment)
    } else if (
      this.jsAuthJudgment('business') ||
      this.jsAuthJudgment('business_agency')
    ) {
      this.reqApiOrganization(params.business_uid)
    }
    this.loadTableData()
  },
  methods: {
    // 权限判断
    jsAuthJudgment(agree_group) {
      return authJudgment(agree_group)
    },
    // 列表请求
    loadTableData(is_initpage = true) {
      const _this = this
      this.loading_start('table')
      if (is_initpage) {
        _this.tableParams.page = 1
      }
      var tableParamsData = { ..._this.tableParams }
      tableParamsData = paramsDeleteNull(tableParamsData, 'business_uid')
      tableParamsData = paramsDeleteNull(tableParamsData, 'o_id')
      tableParamsData = paramsDeleteNull(tableParamsData, 'fuzzy_search')
      tableParamsData = paramsDeleteNull(tableParamsData, 'loan_type')
      tableParamsData = paramsDeleteNull(tableParamsData, 'push_status')
      tableParamsData = paramsDeleteNull(tableParamsData, 'entry_status')
      apiProductlistpage(tableParamsData)
        .then((response) => {
          const result = response
          for (let i = 0; i < result.data.datalist.data.length; i++) {
            result.data.datalist.data[i]['organization_balance'] =  result.data.datalist.data[i]['organization']['balance']
          }
          _this.tableData = result.data.datalist
          this.loading_end('table')
        })
        .catch(function(result) {
          _this.$message.error(result.msg)
          _this.table_loading = false
          _this.tableData.data = null
        })
    },
    // 获取商务人员
    reqApiAgent() {
      const _this = this
      apiAgentList({
        page: 1,
        size: 99,
        status: 'normal',
        group_id: '2,3,5'
      }).then((response) => {
        const result = response.data.datalist.data
        _this.business_select = result
      })
    },
    // 获取机构列表
    reqApiOrganization(business_uid) {
      const _this = this
      this.loading_start('table')
      apiOrganizationSelects({
        page: 1,
        size: 99,
        business_uid: business_uid
      }).then((response) => {
        const result = response.data
        _this.organization_select = result.selects
        this.loading_end('table')
      })
    },
    // 切换商务人员
    changeSelectBusinessuid(business_uid) {
      this.tableParams.o_id = ''
      this.reqApiOrganization(business_uid)
    },
    // 页面跳转
    handleToGoCreate() {
      this.$router.push({ path: '/product/create', query: { id: 0 }})
    },
    // 表格行状态
    tableRowClassName({ row, rowIndex }) {
      if (row['status'] == 'stop') {
        return 'discard-row'
      }
    },
    // 表格操作
    handleTableEdit(index, row) {
      this.$router.push({ path: '/product/update', query: { id: row.id }})
    },
    // 表格恢复
    handleTableRegain(index, row) {
      var _this = this
      var params = {
        id: row.id,
        status: 'normal'
      }

      this.$confirm('是否恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          _this.loading_start('table')
          apiProductUpdatePart(params).then((response) => {
            _this.$message({
              message: '恢复成功',
              type: 'success'
            })
            _this.loadTableData()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 表格删除
    handleTableDelete(index, row) {
      const _this = this

      this.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          _this.loading_start('table')
          apiProductDelete({
            id: row.id
          }).then((response) => {
            this.$message({
              message: response.msg,
              type: 'success'
            })
            _this.loadTableData()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    handleProduceApi(data) {
      console.log(this.$refs.refJsonTree)
      this.$refs.refJsonTree.onOpenView(data)
    },

    // 数量改变
    handleTableSizeChange(val) {
      this.tableParams.size = val
      this.loadTableData(false)
    },
    // 页数改变
    handleTableCurrentChange(val) {
      this.tableParams.page = val
      this.loadTableData(false)
    },
    // 推送 状态改变
    tableUpdateItem(item) {
      var _this = this
      var params = {
        id: item.id,
        push_status: item.push_status,
        entry_status: item.entry_status
      }
      this.$confirm('是否更改状态', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading_start('table')
          apiProductUpdatePart(params).then((response) => {
            _this.loading_end('table')
            _this.$message({
              message: '更新成功',
              type: 'success'
            })
          })
        })
        .catch(() => {
          _this.loadTableData()
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 加载开始...
    loading_start(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.loading[key] = true
          setTimeout(() => {
            this.loading[key] = false
          }, 60000)
        })
      } else {
        this.loading[keys] = true
        setTimeout(() => {
          this.loading[keys] = false
        }, 60000)
      }
    },
    // 加载结束...
    loading_end(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.$nextTick(() => {
            this.loading[key] = false
          })
        })
      } else {
        this.$nextTick(() => {
          this.loading[keys] = false
        })
      }
    }
  }
}
</script>

<style lang="scss">
</style>
